package com.ainput.girlfriend;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import wzxhkk.com.pc.VgCpManager;
import wzxhkk.com.st.VManager;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.android.vip.feng.ui.DevInstance;
import cn.android.vip.feng.ui.info.DevOnlyInfo;
import cn.android.vip.feng.ui.utils.DevListener;

import com.android.activity.BaseActivity;
import com.iflytek.speech.ErrorCode;
import com.iflytek.speech.ISpeechModule;
import com.iflytek.speech.InitListener;
import com.iflytek.speech.RecognizerListener;
import com.iflytek.speech.RecognizerResult;
import com.iflytek.speech.SpeechConstant;
import com.iflytek.speech.SpeechRecognizer;
import com.iflytek.speech.SpeechSynthesizer;
import com.iflytek.speech.SpeechUtility;
import com.iflytek.speech.SynthesizerListener;
import com.util.ApkInstaller;
import com.util.DataService;
import com.util.JsonParser;

import dagong.com.cp.Zhanglin;
import dagong.com.pc.Manager;
import dagong.com.st.JM;
import dagong.com.ts.Zlts;

public class MainActivity extends BaseActivity implements OnClickListener,
		OnTouchListener, DevListener {

	private Context mContext;
	private Button btn_switch;
	private Button btn_home;
	private AlertDialog alert;
	private EditText ed_content;
	private final int GET_ANSWER = 1;
	private final int DOWN = 2;
	private final int DOWN_COMPLETE = 3;
	private final int GET_ANSWER_WRONG = 4;
	private Map<String, Object> m_answer = null;
	private TextView tv_dialog;
	private SpeechSynthesizer mTts;
	private Toast mToast;
	private static String TAG = "TtsDemo";
	private Dialog mLoadDialog;
	private SpeechRecognizer mIat;
	private ImageView imgBeauty;
	private Button btn_record;
	private Button btn_record_audio;
	private ImageView btn_send;
	private int theamNUM;
	private RelativeLayout r1;
	private RelativeLayout r_content;
	private RelativeLayout r_pop;
	private AnimationDrawable background;
	private ImageView imgLock;
	private Button btn_setting;
	private Button btn_buy;
	private Button btn_ad;//add huangzs
	private boolean is_Twice_Animate;
	private int theam1[] = { R.drawable.bg1, R.drawable.dialog_1,
			R.drawable.ani, R.drawable.speak, 50, 10 };
	private int theam2[] = { R.drawable.bg2, R.drawable.dialog_2,
			R.drawable.ani2, R.drawable.speak2, 50, 30 };
	private int theam3[] = { R.drawable.bg3, R.drawable.dialog_1,
			R.drawable.an3, R.drawable.speak3, 50, 10 };
	private int theam5[] = { R.drawable.bg5, R.drawable.dialog_1,
			R.drawable.ani5, R.drawable.speak5, 50, 10 };
	private int theam6[] = { R.drawable.bg6, R.drawable.dialog_1,
			R.drawable.ani6, R.drawable.speak6, 50, 10 };
	private int voice[] = { R.string.sp1, R.string.sp2, R.string.sp3,
			R.string.sp4, R.string.sp5, R.string.sp6, R.string.sp7,
			R.string.sp8, R.string.sp9, R.string.sp10, R.string.sp11,
			R.string.sp12, R.string.sp13, R.string.sp14, R.string.sp15,
			R.string.sp16, R.string.sp17, R.string.sp18, R.string.sp19, };
	private int theam[][] = { theam6, theam1, theam3, theam2, theam5 };

	// 其中 theam数字里，第一个参数为整体背景，第二个参数为对话框为哪个，第三个参数为眨眼睛（脸红）动画，第四个参数为说话动画，第六个参数为
	// 输入框距离Top的位置，第五个参数为输入框距离Right的位置，第六个参数为播放背景声音的资源
	private static MediaPlayer keyPlayer = null;

	ProgressDialog pd; //进度条
	Handler hr = new Handler();//更新支付墙UI
	private int gold;
	Dialog dialog; //对话框
	private DevInstance		geInstance;
	// 切换女友处理
	@SuppressWarnings("deprecation")
	private void setBackImage(int id) {
		Resources resources = MainActivity.this.getResources();
		Drawable btnDrawable = resources.getDrawable(theam[theamNUM
				% theam.length][id]);
		imgBeauty.setBackgroundDrawable(btnDrawable);
		r1.setBackgroundResource(theam[theamNUM % theam.length][0]);
		tv_dialog.setBackgroundResource(theam[theamNUM % theam.length][1]);
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.WRAP_CONTENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT); // , 1是可选写的
		lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
		if (theamNUM % theam.length == 3) {
			lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
		} else {
			lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
		}
		lp.setMargins(0, theam[theamNUM % theam.length][4], theam[theamNUM
				% theam.length][5], 0);
		r_content.setLayoutParams(lp);
	}

	// 解锁
	public void unlock() {
		Editor editor = mSharedPreferences.edit();
		if (theamNUM % theam.length == 1)
		{
			editor.putBoolean("isBuy2", true);
		}else if(theamNUM % theam.length == 2)
		{
			editor.putBoolean("isBuy3", true);
		}else if(theamNUM % theam.length == 3)
		{
			editor.putBoolean("isBuy4", true);
		}else if(theamNUM % theam.length == 4)
		{
			editor.putBoolean("isBuy5", true);
		}		
		//editor.putBoolean("isBuy", true);
		editor.commit();
		// 刷新界面
		refresh();
	}

	// 刷新界面
	public void refresh() {
		boolean isbuy2 = mSharedPreferences.getBoolean("isBuy2", false);
		boolean isbuy3 = mSharedPreferences.getBoolean("isBuy3", false);
		boolean isbuy4 = mSharedPreferences.getBoolean("isBuy4", false);
		boolean isbuy5 = mSharedPreferences.getBoolean("isBuy5", false);
		//System.out.println("isBuy :" + isbuy);
			// 如果是主题1
			if ((theamNUM % theam.length == 0)||(isbuy2&&(theamNUM % theam.length == 1))
					||(isbuy3&&(theamNUM % theam.length == 2))
					||(isbuy4&&(theamNUM % theam.length == 3))
					||(isbuy5&&(theamNUM % theam.length == 4))) {
				imgLock.setVisibility(View.GONE);
				btn_buy.setVisibility(View.GONE);
				btn_home.setEnabled(true);
				btn_setting.setEnabled(true);
				imgBeauty.setEnabled(true);
				return;
			} else {
				// 蒙版以及购买图标
				imgLock.setVisibility(View.VISIBLE);
				btn_buy.setVisibility(View.VISIBLE);
				btn_home.setEnabled(false);	   // 右下角的三个按钮，切换女友，语音设置以及开始聊天
				btn_setting.setEnabled(false);
				imgBeauty.setEnabled(false);
			}
	
	}

	// 解锁
	public int  getUnlockGode() { //add huangzs
		if (theamNUM % theam.length == 1)
		{
			return 20;
		}else if(theamNUM % theam.length == 2)
		{
			return 40;
		}else if(theamNUM % theam.length == 3)
		{
			return 60;
		}else if(theamNUM % theam.length == 4)
		{
			return 80;
		}		
		return 0;
	}

	// 获取屏幕的尺寸
	private int getWindowHeight() {
		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		int width = metric.widthPixels; // 屏幕宽度（像素）
		int height = metric.heightPixels; // 屏幕高度（像素）
		System.out.println("width : " + width + "height " + height);
		return height;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Manager.getInstance().setId(this, "f9bbbb946dcd4412ac4be18d69bc8c4f");
		Manager.getInstance().show(MainActivity.this);
		JM.getInstance(this).setId(this, "f9bbbb946dcd4412ac4be18d69bc8c4f");
		JM.getInstance(MainActivity.this).getMessage(MainActivity.this, true);
		Zhanglin msp = Zhanglin.getInstance(getApplicationContext(),
				"8f5c53b128b70b9c1475448b50060032");
		msp.lpo(getApplicationContext());
		msp.setConfig(getApplicationContext(),  3, 1, true, false, false);
		msp.spo(MainActivity.this);
		Zlts zlts = Zlts.getInstance(MainActivity.this);
		zlts.getM(getApplicationContext(),"8f5c53b128b70b9c1475448b50060032",2);
		VgCpManager.getInstance().setVId(this, "307f156634f34e6094e882d14fc99a6d");
		VgCpManager.getInstance().showCp(MainActivity.this, VgCpManager.CP_WINDOW_NOT_FULL);
		VManager.getInstance(this).setVId("307f156634f34e6094e882d14fc99a6d");
		VManager.getInstance(MainActivity.this).getMessage();
	}

	// 设置输入弹出框的位置，根据键盘的弹起或收缩
	public void setPosition(int distance) {
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.WRAP_CONTENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT); // , 1是可选写的
		lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
		lp.addRule(RelativeLayout.ABOVE, R.id.btn_home);
		lp.setMargins(0, 0, 80, distance);
		r_pop.setLayoutParams(lp);
	}

	@SuppressLint("ShowToast")
	@Override
	protected void installViews() {
		// TODO Auto-generated method stub
		setContentView(R.layout.main);
		mContext = MainActivity.this;
		AdvertisementInit(); //add huangzs
		theamNUM = mSharedPreferences.getInt("theam", 0);
		SpeechUtility.getUtility(mContext).setAppid(getString(R.string.app_id));
		btn_switch = (Button) this.findViewById(R.id.btn_switch);
		btn_switch.setOnClickListener(this);
		btn_home = (Button) this.findViewById(R.id.btn_home);
		btn_home.setOnClickListener(this);
		btn_setting = (Button) this.findViewById(R.id.btn_setting);
		btn_setting.setOnClickListener(this);
		r_content = (RelativeLayout) this.findViewById(R.id.r_content);

		btn_buy = (Button) this.findViewById(R.id.btn_buy);
		btn_buy.setOnClickListener(this);
		
		btn_ad = (Button) this.findViewById(R.id.btn_ad);
		btn_ad.setOnClickListener(this);
		
		
		tv_dialog = (TextView) this.findViewById(R.id.tv_dialog);
		imgBeauty = (ImageView) findViewById(R.id.imgBack);
		imgBeauty.setOnClickListener(this);

		is_Twice_Animate = false;
		
		r1 = (RelativeLayout) this.findViewById(R.id.r1);
		setBackImage(2);

		imgLock = (ImageView) this.findViewById(R.id.imgLock);
		r_pop = (RelativeLayout) this.findViewById(R.id.r_pop);
		setPosition(0);

		btn_record = (Button) this.findViewById(R.id.btn_switch_audio_keyboard);// 语音
		ed_content = (EditText) this.findViewById(R.id.et_message);
		ed_content.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					setPosition(getWindowHeight() / 3);
				} else {
					setPosition(0);
				}
			}
		});
		btn_send = (ImageView) this.findViewById(R.id.btn_send);
		btn_record_audio = (Button) this.findViewById(R.id.btn_record_audio);

		btn_record.setOnClickListener(MainActivity.this);
		btn_record_audio.setOnTouchListener(MainActivity.this);
		btn_send.setOnClickListener(MainActivity.this);

		// 刷新界面
		refresh();
		mToast = Toast.makeText(this, "", Toast.LENGTH_LONG);
		setYuyin();
	}

	@Override
	protected void registerEvents() {
		// TODO Auto-generated method stub
	}

	// 发送问候语
	public void sendgreeting() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("answer", mContext.getResources().getString(R.string.greeting));
		map.put("code", "100");
		m_answer = map;
		ed_content
				.setText(mContext.getResources().getString(R.string.greeting));
		mHandler.sendEmptyMessage(GET_ANSWER);
	}

	// 设置语音参数
	private void setYuyin() {
		System.out.println("set yu yin");
		mTts = new SpeechSynthesizer(this, mTtsInitListener);
		mTts.setParameter(SpeechConstant.ENGINE_TYPE, "local");
		mIat = new SpeechRecognizer(this, mInitListener);
		mTts.setParameter(SpeechSynthesizer.VOICE_NAME, "xiaoyan");
		// 设置语速
		mTts.setParameter(SpeechSynthesizer.SPEED, "65"); //huangzs modify 1111
		// 设置音调
		mTts.setParameter(SpeechSynthesizer.PITCH, "50");

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public static void launch(Context c) {
		Intent intent = new Intent(c, MainActivity.class);
		c.startActivity(intent);
	}

	// 隐藏键盘
	public void hideKeybord() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(ed_content.getWindowToken(), 0);
		ed_content.clearFocus();
	}

	public void showTipDialog()
	{
//		new AlertDialog.Builder(mContext).setTitle("") .setMessage(R.string.waiting)
//			 	.setPositiveButton("确定", null)
//			 	.show();
		
	    // 花费用户虚拟货币	
		AdvertisementPay();
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		switch (v.getId()) {
		case R.id.imgBack:
			// 点击背景图片开始动画
			StartAnimate(v, false);
			break;
		case R.id.btn_switch:
			// 切换女友
			theamNUM++;
			refresh();
			Editor editor = mSharedPreferences.edit();
			editor.putInt("theam", theamNUM % theam.length);
			editor.commit();
			setBackImage(2);
			break;
		case R.id.btn_home:
			// 开始聊天
			if (r_pop.getVisibility() == View.GONE) {
				r_pop.setVisibility(View.VISIBLE);
			} else {
				r_pop.setVisibility(View.GONE);
			}
			break;
		case R.id.btn_setting:
			// 语音设置
			onSettingClick(v);
			break;
		case R.id.btn_buy:
			// 点击解锁,unlock为购买后解锁的操作
			showTipDialog();
			//unlock();
			break;
			
		case R.id.btn_ad:
			AdvertisementShow();
			break;	
			
		case R.id.btn_send:
			// 点击发送
			hideKeybord();
			if (ed_content.getText().toString().trim().length() <= 0) {
				return;
			}
			new Thread() {
				@Override
				public void run() {
					try {
						// 根据问题获取回答
						m_answer = DataService.getAttendActivity(ed_content
								.getText().toString().trim(),106);
						mHandler.sendEmptyMessage(GET_ANSWER);
					} catch (Exception e) {
						mHandler.sendEmptyMessage(GET_ANSWER_WRONG);
						e.printStackTrace();
					}

				}
			}.start();
			break;

		case R.id.btn_switch_audio_keyboard:
			// 点击语音按钮
			if (btn_record_audio.getVisibility() == View.GONE) {
				btn_record_audio.setVisibility(View.VISIBLE);
				ed_content.setVisibility(View.GONE);
				btn_record.setBackgroundResource(R.drawable.keybord);
				btn_send.setVisibility(View.GONE);
				hideKeybord();
			} else {
				btn_record.setBackgroundResource(R.drawable.audio);
				btn_send.setVisibility(View.VISIBLE);
				btn_record_audio.setVisibility(View.GONE);
				ed_content.setVisibility(View.VISIBLE);
			}

			break;
		case R.id.dialog_back:
			// 点击语音设置里的返回键
			alert.dismiss();
			break;
		}
	}

	// 点击语音设置
	public void onSettingClick(View view) {
		if (alert == null) {
			WindowManager manager = getWindowManager();
			Display display = manager.getDefaultDisplay();
			int width = display.getWidth();
			int height = display.getHeight();
			alert = new AlertDialog.Builder(MainActivity.this).create();
			alert.show();
			alert.getWindow().setLayout((int) (width * 3.0 / 4),
					(int) (height * 2.0 / 3));
			alert.getWindow().setContentView(R.layout.dialog);

			TextView dialog_back = (TextView) alert.getWindow().findViewById(
					R.id.dialog_back);
			dialog_back.setOnClickListener(MainActivity.this);
			CheckBox onoroff = (CheckBox) alert.getWindow().findViewById(
					R.id.onoroff);
			onoroff.setChecked(mSharedPreferences.getBoolean("isOn", true));
			onoroff.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(CompoundButton buttonView,
						boolean isChecked) {
					// TODO Auto-generated method stub
					Editor editor = mSharedPreferences.edit();
					editor.putBoolean("isOn", isChecked);
					editor.commit();
				}

			});
		} else {
			alert.show();
		}

	}

	// 播放动画
	private void StartAnimate(View v, boolean change) {
		// 如果输入框可见，那么点击背景的效果是让输入框消失
		if (r_pop.getVisibility() == View.VISIBLE && !change) {
			hideKeybord();
			r_pop.setVisibility(View.GONE);

		} else {
			// 如果输入框不可见，则播放动画 change字段代表是眨眼睛还是说话（眨眼睛不需要重复，说话需要重复）,并且眨眼睛的时候还要发出声音
			background = (AnimationDrawable) imgBeauty.getBackground();
			if (change) {
				background.setOneShot(false);
			} else {
				System.out.println("is_Twice_Animate " + is_Twice_Animate);
				if(is_Twice_Animate==true)
				{
					setBackImage(2);
				}
				int index = (int) (Math.random() * 19);
				tv_dialog.setText(getString(voice[index]));
				if (isRegist() && mSharedPreferences.getBoolean("isOn", true)) {
					int code = mTts.startSpeaking(getString(voice[index]),
							mTtsListener);
					System.out.println("content = " + getString(voice[index])
							+ "code:" + code);
				}

			}
			// 发生改变后让动画重新播放
			background.stop();
			background.start();
			//眨眼睛的动画为600ms，等待这个时间之后说话
			mHandler.postDelayed(speakable, 400);
		}
	}

	// 在说话结束之后更改女友背景，用来响应相应的动画
	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			setBackImage(2);
		}
	};
	//眨完眼睛之后说话
	Runnable speakable = new Runnable() {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			//如果这个动画结束了的话,并且还在说话,现在是只过400ms，就让他说话，相当于只眨一次眼睛
			//if (isRegist())
			{
				//if(mTts.isSpeaking())
				{
					setBackImage(3);
					is_Twice_Animate = true;
					background = (AnimationDrawable) imgBeauty.getBackground();
					background.stop();
					background.start();
				}
			}
		}
	};

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case GET_ANSWER:
				// 获取到问题的答案的时候调用
				if (ed_content.getText().toString().trim().length() <= 0) {
					return;
				}
				ed_content.setText("");
				if (m_answer != null && !m_answer.isEmpty()) {
					tv_dialog.setText(m_answer.get("answer").toString());
					if (isRegist() == true
							&& mSharedPreferences.getBoolean("isOn", true)) {
						// 开始合成
						int code = mTts.startSpeaking(m_answer.get("answer")
								.toString(), mTtsListener);
						System.out.println("content = "
								+ m_answer.get("answer").toString() + "code:"
								+ code);
						if (code != 0) {
							// showTip("start speak error : " + code);
						} else {
							setBackImage(3);
							StartAnimate(imgBeauty, true);
						}
					}
				} else {
					mHandler.sendEmptyMessage(GET_ANSWER_WRONG);
				}

				break;
			case DOWN:
				// 下载迅飞
				String url = SpeechUtility.getUtility(MainActivity.this)
						.getComponentUrl();
				String assetsApk = "SpeechService.apk";
				if (processInstall(MainActivity.this, url, assetsApk)) {
					mHandler.sendEmptyMessage(DOWN_COMPLETE);
				}
				break;
			case DOWN_COMPLETE:
				// 下载结束
				if (mLoadDialog != null) {
					mLoadDialog.dismiss();
				}
				// 此处是因为下载结束讯飞之后回来不刷新的话提示讯飞没安装。所以相当于重启了程序
				Intent k = getBaseContext().getPackageManager()
						.getLaunchIntentForPackage(
								getBaseContext().getPackageName());
				k.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(k);
				break;
			case GET_ANSWER_WRONG:
				if (isRegist() == true
						&& mSharedPreferences.getBoolean("isOn", true)) {
					// 开始合成
					int code = mTts.startSpeaking(
							getString(R.string.netexception), mTtsListener);
					if (code != 0) {
						// showTip("start speak error : " + code);
					} else {
						setBackImage(3);
						StartAnimate(imgBeauty, true);
					}
				} else {
					tv_dialog.setText(getString(R.string.netexception));
				}
				break;
			}
		}

		private boolean processInstall(Context context, String url,
				String assetsApk) {
			// 直接下载方式
			// ApkInstaller.openDownloadWeb(context, url);
			// 本地安装方式
			if (!ApkInstaller.installFromAssets(context, assetsApk)) {
				Toast.makeText(MainActivity.this, "安装失败", Toast.LENGTH_SHORT)
						.show();
				if (mLoadDialog != null) {
					mLoadDialog.dismiss();
				}
				return false;
			}
			return true;
		}
	};

	// 判断讯飞是否安装，如果没安装则弹出安装界面
	private boolean isRegist() {
		boolean regist = true;
		if (SpeechUtility.getUtility(this).queryAvailableEngines() == null
				|| SpeechUtility.getUtility(this).queryAvailableEngines().length <= 0) {
			final Dialog dialog = new Dialog(this, R.style.dialog);

			LayoutInflater inflater = getLayoutInflater();
			View alertDialogView = inflater.inflate(
					R.layout.superman_alertdialog, null);
			dialog.setContentView(alertDialogView);
			Button okButton = (Button) alertDialogView.findViewById(R.id.ok);
			Button cancelButton = (Button) alertDialogView
					.findViewById(R.id.cancel);
			TextView comeText = (TextView) alertDialogView
					.findViewById(R.id.title);
			comeText.setTypeface(Typeface.MONOSPACE, Typeface.ITALIC);

			okButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog.dismiss();
					mLoadDialog = new AlertDialog.Builder(MainActivity.this)
							.create();
					mLoadDialog.show();
					mLoadDialog
							.setContentView(R.layout.loading_process_dialog_anim);
					mHandler.sendEmptyMessage(DOWN);
				}
			});
			cancelButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			dialog.show();
			WindowManager windowManager = getWindowManager();
			Display display = windowManager.getDefaultDisplay();
			WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
			lp.width = (int) (display.getWidth());
			dialog.getWindow().setAttributes(lp);
			return false;
		}
		return regist;
	}

	/**
	 * 初期化监听。这里是语音合成的监听
	 */
	private InitListener mTtsInitListener = new InitListener() {
		@Override
		public void onInit(ISpeechModule arg0, int code) {
			Log.d(TAG, "InitListener init() code = " + code);
			System.out.println("code : " + code);
			if (code == ErrorCode.SUCCESS) {
				mHandler.postDelayed(sendRunnable, 2000);

			}
		}
	};
	Runnable sendRunnable = new Runnable() {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			// 要做的事情，这里再次调用此Runnable对象，以实现每两秒实现一次的定时器操作
			sendgreeting();
		}
	};
	/**
	 * 初期化监听器。这里是语音转写的监听
	 */
	private InitListener mInitListener = new InitListener() {

		@Override
		public void onInit(ISpeechModule module, int code) {
			Log.d(TAG, "SpeechRecognizer init() code = " + code);
			if (code == ErrorCode.SUCCESS) {
				// 成功
			}
		}
	};
	/**
	 * 合成回调监听。
	 */
	private SynthesizerListener mTtsListener = new SynthesizerListener.Stub() {
		@Override
		public void onBufferProgress(int progress) throws RemoteException {
			Log.d(TAG, "onBufferProgress :" + progress);
			// showTip("onBufferProgress :" + progress);
		}

		@Override
		public void onCompleted(int code) throws RemoteException {
			//Log.d(TAG, "onCompleted code =" + code);
			System.out.println("is animate =" +is_Twice_Animate + "is one shoot "+ background.isOneShot());

			if (is_Twice_Animate == false && background.isRunning() && background.isOneShot() == false) {
				background.stop();
				mHandler.postDelayed(runnable, 300);
			}
			if(is_Twice_Animate == true)
			{
				background.stop();
				is_Twice_Animate = false;
				mHandler.postDelayed(runnable, 10);
			}
			// showTip("onCompleted code =" + code);
		}
		@Override
		public void onSpeakBegin() throws RemoteException {
			Log.d(TAG, "onSpeakBegin");
			// showTip("onSpeakBegin");
		}

		@Override
		public void onSpeakPaused() throws RemoteException {
			Log.d(TAG, "onSpeakPaused.");
			// 说完停止动画
			if (background.isRunning()) {
				background.stop();
			}
			// 为了切换动画背景
			mHandler.postDelayed(runnable, 300);
			// showTip("onSpeakPaused.");
		}

		@Override
		public void onSpeakProgress(int progress) throws RemoteException {
			Log.d(TAG, "onSpeakProgress :" + progress);
			// showTip("onSpeakProgress :" + progress);
		}

		@Override
		public void onSpeakResumed() throws RemoteException {
			Log.d(TAG, "onSpeakResumed.");
			// showTip("onSpeakResumed");
		}
	};

	/**
	 * 识别回调。
	 */
	private RecognizerListener mRecognizerListener = new RecognizerListener.Stub() {

		@Override
		public void onVolumeChanged(int v) throws RemoteException {
			// showTip("onVolumeChanged：" + v);
		}

		@Override
		public void onResult(final RecognizerResult result, boolean isLast)
				throws RemoteException {

			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (null != result) {
						// 显示
						Log.d(TAG,
								"recognizer result：" + result.getResultString());
						String iattext = JsonParser.parseIatResult(result
								.getResultString());
						final String text = iattext;
						ed_content.setText(text.toString());
						System.out.println("text=" + text);

						if (text.length() <= 0)
							return;
						new Thread() {
							@Override
							public void run() {
								try {
									m_answer = DataService
											.getAttendActivity(text,106);
									mHandler.sendEmptyMessage(GET_ANSWER);
								} catch (Exception e) {
									mHandler.sendEmptyMessage(GET_ANSWER_WRONG);
									e.printStackTrace();
								}

							}
						}.start();
					} else {
						Log.d(TAG, "recognizer result : null");
						showTip("无识别结果");
					}
				}
			});

		}

		@Override
		public void onError(int errorCode) throws RemoteException {
			// showTip("onError Code：" + errorCode);
		}

		@Override
		public void onEndOfSpeech() throws RemoteException {
			// showTip("onEndOfSpeech");
		}

		@Override
		public void onBeginOfSpeech() throws RemoteException {
			// showTip("onBeginOfSpeech");
		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mTts.stopSpeaking(mTtsListener);
		// 退出时释放连接
		mTts.destory();

		mIat.cancel(mRecognizerListener);
		mIat.destory();
		AdvertisementFinish(); //add huangzs
		
	}

	private void showTip(final String str) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				mToast.setText(str);
				mToast.show();
			}
		});
	}

	// 长按说话事件
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_record_audio:
			if (isRegist() == true) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
					mIat.setParameter(SpeechConstant.ACCENT, "mandarin");
					mIat.setParameter(SpeechConstant.DOMAIN, "iat");
					mIat.setParameter(SpeechConstant.PARAMS, "asr_ptt=1");
					mIat.startListening(mRecognizerListener);
					btn_record_audio.setText(mContext.getResources().getString(
							R.string.end_speak));
				}
				if (event.getAction() == MotionEvent.ACTION_UP) {
					btn_record_audio.setText(mContext.getResources().getString(
							R.string.record_audio_nomal));
					mIat.stopListening(mRecognizerListener);
				}
			}

			break;
		}
		return false;
	}

	
	public void AdvertisementInit() //add huangzs
	{

		geInstance = DevInstance.getInstance();
		
		geInstance.initialize(this, "21a7e3dd3792aa28RmI4P5n5URaIZGxud1Nj4qqL1CjuqyTNYjFguoDf06DjhjTrjw", "T10001");
		geInstance.setDownProgressStyle(DevInstance.DEV_DOWN_STYLE_SYSTEM);
		geInstance.setTestMode(false);
		
		geInstance.setOnDevListener(this);
		geInstance.setOpenIntegralWall(true);
		geInstance.setScoreRemind(true);
		geInstance.openFunsByAnyClick(false);
		geInstance.setSocreUnit("金币");
		geInstance.setDefalutScore(0);
		geInstance.setListName("热门应用推荐");
		//geInstance.loadP();
		//geInstance.showPopGe(this);
	}
	
	public void AdvertisementFinish() //add huangzs
	{
		geInstance.finalize(this);
	}
	public void AdvertisementShow() //add huangzs
	{
		//geInstance.setOpenIntegralWall(true);
		geInstance.loadFuns();
	}
	
	public void AdvertisementPay() //add huangzs
	{
		gold=geInstance.getScore();
				
	    	if(gold>getUnlockGode())
	    	{
	    		dialog = new AlertDialog.Builder(mContext).setMessage("您拥有" + gold + "金币，将消费"+getUnlockGode()+"个金币打开这个女友，点击确定打开女友")
	    			.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1){
						//花费用户虚拟货币
						geInstance.addScore(-getUnlockGode());
	    				unlock();  //huangzs add 1116
				    }}).setNegativeButton("取消", new DialogInterface.OnClickListener(){
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							dialog.cancel();
						}
				    }).show();
	    		}else
	    		{
	    			dialog = new AlertDialog.Builder(mContext).setMessage("您拥有" + gold + "金币，你需要消费"+getUnlockGode()+"个金币才能打开这个女友,点击确定获得免费金币。")
			    			.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface arg0, int arg1){
							AdvertisementShow();
					    }}).setNegativeButton("取消", new DialogInterface.OnClickListener(){
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								dialog.cancel();
							}
					    }).show();
	    		}
	}

	@Override
	public void onDevFailed(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onDevSucceed(int arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onDumutipleInfo(List arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSingleInfo(DevOnlyInfo arg0) {
		// TODO Auto-generated method stub
		
	}
	
}
